<template>
  <view class="container" :style="appThemeStyle">
    <!-- 标题 -->
    <view class="page-title">个人信息</view>
    <!-- 表单组件 -->
    <view class="form-wrapper">
      <u-form :model="form" ref="uForm" label-width="140rpx">
        <u-form-item label="头像">
          <button class="btn-normal" open-type="chooseAvatar" @click="onClickAvatar()" @chooseavatar="onChooseAvatar">
            <avatar-image :url="avatarUrl" :width="100" />
          </button>
        </u-form-item>
        <u-form-item label="昵称" prop="nickName">
          <u-input v-model="form.nickName" type="nickname" maxlength="30" placeholder="请输入昵称" @input="onInputNickName"
            @blur="onInputNickName" />
        </u-form-item>
		<u-form-item label="手机号" prop="mobile">
		  <u-input v-model="form.mobile" type="mobile" maxlength="30" placeholder="请输入手机号" />
		</u-form-item>
		<u-form-item label="性别" prop="gender" @click="showGenderSheet"><u-input @click="showGenderSheet" v-model="form.gender" type="select"  placeholder="请输入性别"/></u-form-item>
		<u-form-item label="简介" prop="intro"><u-input v-model="form.intro" placeholder="请输入简介"/></u-form-item>
      </u-form>
	  <u-action-sheet
		:list="genderList"
		v-model="showSheet"
		@click="selectGender"
	  ></u-action-sheet>
    </view>

    <!-- 操作按钮 -->
    <view class="footer">
      <view class="btn-wrapper">
        <view class="btn-item btn-item-main" :class="{ disabled }" @click="handleSubmit()">保存</view>
      </view>
    </view>
  </view>
</template>

<script>
  import store from '@/store'
  import AvatarImage from '@/components/avatar-image'
  import * as UserApi from '@/api/user'
  import * as UploadApi from '@/api/upload'
  import {
		uploadFile, getCommonToken, uploadFile2
  } from '@/utils/upload.js' //引入方法
  import * as FindApi from '@/api/find'
  // 表单验证规则
  const rules = {
    nickName: [{
      required: true,
      message: '请输入用户昵称',
      trigger: ['blur', 'change']
    }]
	// mobile: [
	// 	{
	// 		required: true, 
	// 		message: '请输入手机号',
	// 		trigger: ['change','blur'],
	// 	},
	// 	 {  validator: (rule, value, callback) => {
	// 			  if (!value) {
	// 				return callback(new Error('手机号不能为空'));
	// 			  }
	// 			  const phoneReg = /^1[3-9]\d{9}$/; // 中国的手机号码正则表达式，11位数字，以1开头，第二位是3-9之间的任意数字
	// 			  if (!phoneReg.test(value)) {
	// 				return callback(new Error('请输入有效的手机号码'));
	// 			  }
	// 			  callback(); // 验证通过，返回空值
	// 	    },
	// 		trigger: 'blur'
	// 	  }
	// ]
  }

  export default {
    components: {
      AvatarImage
    },
    data() {
      return {
        // 按钮禁用
        disabled: false,
        // 头像路径 (用于显示)
        avatarUrl: '',
        // 临时图片 (用于上传)
        tempFile: null,
        // 表单数据
        form: {
          avatar: '',
          nickName: '',
		  mobile: '', // 手机号
		  gender: '', //性别
		  genderId: '', //性别id
		  intro: '', //简介
        },
        // 验证规则
        rules,
		showSheet: false,
	    genderList: [
			{ text: '男', id: 1 },
			{ text: '女', id: 2 }
		],
      }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad() {
      // 获取当前用户信息
      this.getUserInfo()
	  // this.getCommonStsToken()
    },

    // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
    onReady() {
      this.$refs.uForm.setRules(this.rules)
    },

    methods: {
	  validatePhone(rule, value, callback) {
		  if (!value) {
			return callback(new Error('手机号不能为空'));
		  }
		  const phoneReg = /^1[3-9]\d{9}$/; // 中国的手机号码正则表达式，11位数字，以1开头，第二位是3-9之间的任意数字
		  if (!phoneReg.test(value)) {
			return callback(new Error('请输入有效的手机号码'));
		  }
		  callback(); // 验证通过，返回空值
	  },
      // 获取当前用户信息
      getUserInfo() {
        const app = this
        UserApi.info()
          .then(result => {
            const userInfo = result.data
            app.avatarUrl = userInfo.avatar
			app.form = {
			  avatar: userInfo.avatar,
			  nickName: userInfo.nick_name,
			  mobile: userInfo.mobile, // 手机号
			  gender: userInfo.gender == 1 ? '男' :  userInfo.gender == 2 ? '女' : '', //性别
			  genderId: userInfo.gender, //性别id
			  intro: userInfo.intro //简介
			}
          })
      },
      // 点击头像按钮事件
      onClickAvatar() {
        // #ifdef MP-WEIXIN
        return
        // #endif
        this.chooseImage()
      },

      // 选择头像事件 - 仅限微信小程序
      onChooseAvatar({ detail }) {
	    console.log(detail, 'detail')
        // #ifdef MP-WEIXIN
        const app = this
        app.avatarUrl = detail.avatarUrl
        app.tempFile = { path: app.avatarUrl }
        // #endif
      },
      // 获取上传临时密钥
	  getCommonStsToken() {
		FindApi.commonToken({})
		  .then(result => {
			getCommonToken(result)
		  })
	  },
      // 选择图片
      chooseImage() {
        const app = this
        // 选择图片
        uni.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success({ tempFiles }) {
			console.log(tempFiles, 'tempFiles')
            app.tempFile = tempFiles[0]
            app.avatarUrl = app.tempFile.path
          }
        });
      },

      // 上传图片
      uploadFiles() {
        const app = this
		let startIndex = app.tempFile.path.lastIndexOf('.')
		let urls = app.tempFile.path.substring(startIndex);
		const [y, m, d] = [new Date().getFullYear(), String(new Date().getMonth() + 1).padStart(2, '0'), String(new Date().getDate()).padStart(2, '0')];
		const fileName = `images/console/${y}${m}${d}/${Date.now()}_${Math.random().toString(36).substr(2, 6)}${urls}`; // 生成文件名
		console.log(app.tempFile,fileName, urls)
		return FindApi.commonToken({})
		  .then(result => {
			  //#ifdef H5
				  return uploadFile2(result, app.tempFile,fileName).then(cosRes => {
					console.log(cosRes) // 拿到腾讯云图片地址
					if(cosRes) {
						let startIndex = cosRes.indexOf('/') + 1;
						let url_l = cosRes.substring(startIndex);
						app.form.avatar = url_l
						app.tempFile = null
						app.$toast('上传成功')
						return true
					}
				  }).catch(() => {
					  return false
				  })
			  //#endif
			  // #ifdef APP-PLUS || MP-WEIXIN 
			  return uploadFile(result, app.tempFile.path,fileName).then(cosRes => {
					console.log(cosRes) // 拿到腾讯云图片地址
					if(cosRes) {
						let startIndex = cosRes.indexOf('/') + 1;
						let url_l = cosRes.substring(startIndex);
						app.form.avatar = url_l
						app.tempFile = null
						app.$toast('上传成功')
						return true
					}
			  }).catch(() => {
				  return false
			  })
			  // #endif
		  })
      },
	  showGenderSheet() {
		  console.log('showGenderSheet')
		  this.showSheet = true;
	  },
	  selectGender(index) {
		  this.form.gender = this.genderList[index].text;
		  this.form.genderId = this.genderList[index].id
		  this.showSheet = false;
	  },
      // 确认修改
      async handleSubmit() {
        const app = this

        // 判断是否重复提交
        if (app.disabled === true) return
        app.$refs.uForm.validate(async valid => {
          if (!valid) return
          // 按钮禁用
          app.disabled = true
          // 先上传头像图片
          if (app.tempFile && !await app.uploadFiles()) {
            app.$toast('很抱歉，头像上传失败')
            app.disabled = false
            return
          }
		  let obj = {
		  	avatar: app.form.avatar,
		  	gender: app.form.genderId,
		  	intro: app.form.intro,
		  	mobile: app.form.mobile,
		  	nickName: app.form.nickName
		  }
		  console.log('提交内容', app.form,obj)
          // 提交保存个人信息
          UserApi.personal(obj)
            .then(result => {
              app.$toast(result.message)
              setTimeout(() => {
                app.disabled = false
                uni.navigateBack()
              }, 1500)
            })
            .catch(err => app.disabled = false)
        })
      },

      // 绑定昵称输入框 (用于微信小程序端快速填写昵称能力)
      onInputNickName(val) {
        if (val) {
          this.form.nickName = val
        }
      }

    }
  }
</script>

<style>
  page {
    background: #f7f8fa;
  }
</style>
<style lang="scss" scoped>
  .container {}

  .page-title {
    width: 94%;
    margin: 0 auto;
    padding-top: 40rpx;
    font-size: 28rpx;
    color: rgba(69, 90, 100, 0.6);
  }

  .form-wrapper {
    margin: 20rpx auto 20rpx auto;
    padding: 0 40rpx;
    width: 94%;
    box-shadow: 0 1rpx 5rpx 0px rgba(0, 0, 0, 0.05);
    border-radius: 16rpx;
    background: #fff;
  }

  /* 底部操作栏 */

  .footer {
    margin-top: 80rpx;

    .btn-wrapper {
      height: 100%;
      // display: flex;
      // align-items: center;
      padding: 0 20rpx;
    }

    .btn-item {
      flex: 1;
      font-size: 28rpx;
      height: 86rpx;
      color: #fff;
      border-radius: 50rpx;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .btn-item-wechat {
      background: #0ba90b;
      margin-bottom: 26rpx;
    }

    .btn-item-main {
      background: linear-gradient(to right, $main-bg, $main-bg2);
      color: $main-text;

      // 禁用按钮
      &.disabled {
        opacity: 0.6;
      }
    }

  }
</style>